package com.gzhryc.shared_device.oem.h5.mng.controllers.place;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.bxscn.code.dao.db.PortableEnergyBattery;
import com.gzhryc.shared_device.bxscn.code.services.PortableEnergyBatteryService;
import com.gzhryc.shared_device.common.device.dao.db.Device;
import com.gzhryc.shared_device.common.device.services.DeviceService;
import com.gzhryc.shared_device.common.device.services.dto.DeviceSearch;
import com.gzhryc.shared_device.oem.code.BaseConstants;
import com.gzhryc.shared_device.oem.code.device.EDeviceFunCode;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.code.user.services.UserService;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

public class PlaceDeviceController {

    @Route(value = {"/place/device/list.html"})
    public String list(HttpServletRequest request) {
        Long placeId = WebUtils.getLong(request, "placeId");
        PlacePhysicalStore place = PlacePhysicalStoreService.self().getById(placeId);
        WebUtils.setAttribute(request,place);
        request.setAttribute("deviceFuncCodeList", EDeviceFunCode.values());
        return "/place/device/list.html";
    }

    @Route(value = "/place/device/list.data")
    public ListResult<Device> listData(HttpServletRequest request) {
        ListResult<Device> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        DeviceSearch search = WebUtils.getParameter(request, DeviceSearch.class);
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
        if (search.getPlaceId() != null) {
            result.getBody().setTotal(DeviceService.self().countBySearch(search));
            result.getBody().setData(DeviceService.self().findBySearch(search, pageNo, pageLimit));
            
            if(BaseConstants.getBXSCN()) {
            	List<PortableEnergyBattery> batteryList = PortableEnergyBatteryService.self().findJoinByPlaceId(search.getPlaceId());
            	if(batteryList != null && batteryList.size() > 0) {
            		if(result.getBody().getData() == null) {
            			result.getBody().setData(new ArrayList<>());
            		}
            		for(PortableEnergyBattery battery : batteryList) {
            			Device device = new Device();
            			device.setDeviceSn(battery.getDeviceSn());
            			device.setDeviceTypeName(battery.getTypeName());
            			device.setPlaceId(battery.getPlaceId());
            			device.setUserId(battery.getUserId());
            			device.setUserName(battery.getUserName());
            			device.setUserPhone(battery.getUserPhone());
            			device.setDeployDate(battery.getDeployDate());
            			device.setBindNote(battery.getBindNote());
            			device.setDeviceFunNames("应急电源");
            			result.getBody().getData().add(device);
            		}
            	}
            }
            
            
            if (result.getBody().getData() != null && result.getBody().getData().size() > 0) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        }
        return result;
    }

    @Route(value = {"/place/device/add.html"})
    public String add(HttpServletRequest request) {
        Long placeId = WebUtils.getLong(request, "placeId");
        PlacePhysicalStore place = PlacePhysicalStoreService.self().getById(placeId);
        request.setAttribute("place", place);
        return "/place/device/edit.html";
    }

    @Route(value = {"/place/device/add.do"})
    public AjaxResult doAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "部署失败，请稍后再试");
        Long placeId = WebUtils.getLong(request, "placeId");
        String deviceSn = WebUtils.getString(request, "deviceSn");
        String bindNote = WebUtils.getString(request, "bindNote");
        if (placeId != null && StringTools.isNotBlank(deviceSn)) {
            PlacePhysicalStore place = PlacePhysicalStoreService.self().getJoinById(placeId);
            if (place == null) {
                result.setMsg("未找到网点信息");
                return result;
            }

            Device device = DeviceService.self().getByDeviceSn(deviceSn);
            if (device != null) {
            	if (device.getPlaceId() != null) {
                    result.setMsg("设备已部署");
                    return result;
                }
            	
            	device.setPlaceId(placeId);
                device.setPlaceName(place.getName());
                device.setUserId(place.getUserId());
                device.setUserName(place.getUser().getName());
                device.setUserPhone(place.getUser().getPhone());
                device.setProvince(place.getProvince());
                device.setCity(place.getCity());
                device.setCityArea(place.getCityArea());
                device.setAreaCode(place.getAreaCode());
                device.setBindNote(bindNote);

                try {
                    if (DeviceService.self().deploy(device, PlacePhysicalStoreService.self())) {
                        result.setCode(DtoConstants.SUCCESS, null);
                    }
                } catch (LogicException e) {
                    result.setMsg(e.getMessage());
                }
               
            }else {
            	PortableEnergyBattery battery = PortableEnergyBatteryService.self().getByDeviceSn(deviceSn);
            	if(battery != null) {
            		try {
						if(PortableEnergyBatteryService.self().deploy(battery, place, bindNote, PlacePhysicalStoreService.self())) {
							result.setCode(DtoConstants.SUCCESS, null);
						}
					} catch (LogicException e) {
						result.setMsg(e.getMessage());
					}
            	}else {
            		 result.setMsg("设备不存在");
                     return result;
            	}
            }
        }
        return result;
    }

    @Route(value = {"/place/device/bind_note/update.html"})
    public String updateBindNote(HttpServletRequest request) {
        return "/place/device/bind_note.html";
    }

    @Route(value = {"/place/device/bind_note/update.do"})
    public AjaxResult doUpdateBindNote(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改失败，请稍后再试");
        String deviceSn = WebUtils.getString(request, "deviceSn");
        String bindNote = WebUtils.getString(request, "bindNote");
        if (StringTools.isNotBlank(deviceSn)) {
        	 Device device = DeviceService.self().getByDeviceSn(deviceSn);
             if (device != null) {
	            if (DeviceService.self().updateBindNote(deviceSn, bindNote)) {
	                result.setCode(DtoConstants.SUCCESS, null);
	            }
             }else {
            	 PortableEnergyBattery battery = PortableEnergyBatteryService.self().getByDeviceSn(deviceSn);
             	if(battery != null) {
             		if(PortableEnergyBatteryService.self().updateBindNote(deviceSn, bindNote)) {
             			result.setCode(DtoConstants.SUCCESS, null);
             		}
             	}else {
             		result.setMsg("设备不存在");
                     return result;
             	}
             }
        }
        return result;
    }

    @Route(value = {"/place/device/undeploy.do"})
    public AjaxResult doUndeploy(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "移除失败，请稍后再试");
        String deviceSn = WebUtils.getString(request, "deviceSn");
        try {
            Device device = DeviceService.self().getByDeviceSn(deviceSn);
            if (device != null) {
            	if (device.getPlaceId() == null) {
                    result.setMsg("设备未部署");
                    return result;
                }
            	
            	if (DeviceService.self().undeploy(device,PlacePhysicalStoreService.self())) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            }else {
            	PortableEnergyBattery battery = PortableEnergyBatteryService.self().getByDeviceSn(deviceSn);
            	if(battery != null) {
            		if(PortableEnergyBatteryService.self().undeploy(battery)) {
            			result.setCode(DtoConstants.SUCCESS, null);
            		}
            	}else {
            		result.setMsg("设备不存在");
                    return result;
            	}
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 批量部署
     * @param request
     * @return
     */
    @Route(value = { "/place/device/batch/deploy.html" })
    public String setBelong(HttpServletRequest request) {
        return "/place/device/deploy.html";
    }

    @Route(value = { "/place/device/batch/deploy.do" })
    public AjaxResult doSetBelong(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "部署设备失败");
        Long placeId = WebUtils.getLong(request, "placeId");
        String batchId = WebUtils.getString(request,"batchId");
        Integer setStartNum = WebUtils.getInteger(request, "setStartNum");
        Integer setTotal = WebUtils.getInteger(request, "setTotal");
        Integer strategyType = WebUtils.getInteger(request,"strategyType");
        if(StringTools.isNotBlank(batchId) && setStartNum != null && setTotal != null) {
            try {
                if(DeviceService.self().deploy(batchId,strategyType,setStartNum,setTotal,placeId,
                		PlacePhysicalStoreService.self(),UserService.self())){
                    result.setCode(DtoConstants.SUCCESS,null);
                    return result;
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }else {
            result.setMsg("参数错误");
        }
        return result;
    }
}
